* **************************************************************************** *
* Sierra Leone - Social Signaling and Childhood Immunization
* Table: Balance on Characteristics of 24 months Sample
* **************************************************************************** *
/*
** Purpose:  Create Balance Table on Characteristics of 24 months Analysis Sample

*/
* **************************************************************************** *
* **************************************************************************** *


	use   "${Replicate_SocialSignals_dtaInter}/Balance_ListingSample.dta", clear

	* Keep only children that were eligible for follow-up

	keep if proportion_flwup==1 | (surveyed_flwup==1 & pikin_type_flwup==1)

	* Drop existing matrices
	cap mat drop _all


	lab var good_memory   "Mother's ability to recall last vaccine"
	lab var mean_distance "Distance to clinic (in miles)"

	* --------------------------------------------------------------------------
	* Run balance in 2 steps: (1) ttest differences, (2) p-values


	local   FollowUpVars  = "  surveyed_flwup a04b_flwup_2 a04b_flwup_1 a04b_flwup_3 a04b_flwup_4 "
	local   AgeCardVars   = " age_listing card "

	local   CardVars      = " quality_card "
	local   MemoryVars    = " good_memory "

	local   treatVar      = " intervention_arm "
	local   strataVar     = " strata "
	local   clusterVar    = " clinic_code "
	local   covariates    = " anc2 anc3 anc4 "





	* **************************************************************************** *
	* 2.) Follow-up Variables
	* **************************************************************************** *

	* ---------------------------------------------------------------------------- *
	* Compute ttest  mean differences
	* ---------------------------------------------------------------------------- *

	* (1) ttest mean differences

	preserve

		iebaltab  `FollowUpVars',  ///
		vce(cluster `clusterVar') ///
		grpvar(`treatVar') fixedeffect(`strataVar') covariates(`covariates') ///
		grplabels(1 Control @ 2 Uninformative @ 3 Signal at 4  @ 4 Signal at 5 ) order(1 2 3 4) ///
		fmissok feqtest pftest covarmissok    fnoobs   ${BalStars} ///
		rowvarlabels onerow ///
		tblnonote ///
		browse ///
		replace

		drop in 1/3

		gen     count = _n

		* Temporary save the table output
		tempfile  ttest_diff
		save   	 `ttest_diff'

	restore


	* ---------------------------------------------------------------------------- *
	* Compute ttest p-values
	* ---------------------------------------------------------------------------- *

	*  p-values

	preserve

		#d ;
		iebaltab   `FollowUpVars',
		vce(cluster `clusterVar')
		grpvar(`treatVar') fixedeffect(`strataVar') covariates(`covariates') ///
		grplabels(1 Control @ 2 Uninformative @ 3 Signal at 4  @ 4 Signal at 5 ) order(1 2 3 4)
		fmissok feqtest pboth covarmissok   fnoobs   ${BalStars}
		rowvarlabels onerow
		tblnonote
		browse
		replace
		;
		#d	cr

		drop in 1/3
		gen     count = _n

		drop    v2-v5

		foreach    variable of numlist 6(1)11 {
		replace v`variable' = "[" + v`variable' + "]"     if v`variable' !=""
		}
		replace count = count +1

		drop if v1 == ""

		* Temporary save the table output
		tempfile  ttest_pvals
		save   	 `ttest_pvals'
	restore



	* ---------------------------------------------------------------------------- *
	* Merge ttest differences & p-values
	* ---------------------------------------------------------------------------- *

	preserve

		use `ttest_diff', clear

		merge 1:1 count using `ttest_pvals', gen(Merge) keepusing(v6-v11) update


		* Compute Number of Observations and Clinics below each test:
		foreach column in 1 2 3 4 {
		local   col_1 = `column'+1
		gen     n`column' = v`col_1'           if inlist(v1,"N","Clusters")
		}

		foreach column in 1 2 3 4  {
		destring n`column', replace
		}

		* Generate new columns for difference calculations:
		foreach column of numlist 6(1)11 {
		gen      n`column' = .
		}

		* Compute the new N's:
		replace  n6  = n1+n2
		replace  n7  = n1+n3
		replace  n8  = n1+n4
		replace  n9  = n2+n3
		replace  n10 = n2+n4
		replace  n11 = n3+n4

		* String and replace:
		foreach column of numlist 6(1)11 {
		tostring n`column', replace
		}

		foreach column of numlist 6(1)11 {
		replace v`column' = n`column'               if n`column' !="." & v`column' ==""
		}

		foreach column of numlist 2(1)5 {
		replace v`column' = ""                      if v`column' !="" & inlist(v1,"N","Clusters")
		}

		* Keep only the Control Group Mean:
		drop v3-v5
		drop n1-n11

		drop count Merge

		replace v1 = "Observations"         if v1 == "N"
		replace v1 = "Clinics"              if v1 == "Clusters"


		local    followup_fileNum = 0

		dataout, save("${Replicate_SocialSignals_ATables}/followup_balance_at24m_`followup_fileNum'.tex") ///
		replace tex nohead noauto

	restore



	* **************************************************************************** *
	* 3.) Age & Vaccine card Ownership
	* **************************************************************************** *

	* ---------------------------------------------------------------------------- *
	* Compute ttest  mean differences
	* -------------


	* Keep only mop-up children who have been interviewed in the follow up
	keep if pikin_type_flwup==1 
	count



	*--------------------------------------------------------------- *

	* (1) ttest mean differences

	preserve

		iebaltab  `AgeCardVars',  ///
		vce(cluster `clusterVar') ///
		grpvar(`treatVar') fixedeffect(`strataVar') covariates(`covariates') ///
		grplabels(1 Control @ 2 Uninformative @ 3 Signal at 4  @ 4 Signal at 5 ) order(1 2 3 4) ///
		fmissok feqtest pftest covarmissok    fnoobs   ${BalStars} ///
		rowvarlabels onerow ///
		tblnonote ///
		browse ///
		replace

		drop in 1/3

		gen     count = _n

		* Temporary save the table output
		tempfile  ttest_diff
		save   	 `ttest_diff'

	restore


	* ---------------------------------------------------------------------------- *
	* Compute ttest p-values
	* ---------------------------------------------------------------------------- *

	*  p-values

	preserve

		#d ;
		iebaltab   `AgeCardVars',
		vce(cluster `clusterVar')
		grpvar(`treatVar') fixedeffect(`strataVar') covariates(`covariates') ///
		grplabels(1 Control @ 2 Uninformative @ 3 Signal at 4  @ 4 Signal at 5 ) order(1 2 3 4)
		fmissok feqtest pboth covarmissok   fnoobs   ${BalStars}
		rowvarlabels onerow
		tblnonote
		browse
		replace
		;
		#d	cr

		drop in 1/3
		gen     count = _n

		drop    v2-v5

		foreach    variable of numlist 6(1)11 {
		replace v`variable' = "[" + v`variable' + "]"     if v`variable' !=""
		}
		replace count = count +1

		drop if v1 == ""

		* Temporary save the table output
		tempfile  ttest_pvals
		save   	 `ttest_pvals'

	restore



	* ---------------------------------------------------------------------------- *
	* Merge ttest differences & p-values
	* ---------------------------------------------------------------------------- *


	preserve

		use `ttest_diff', clear

		merge 1:1 count using `ttest_pvals', gen(Merge) keepusing(v6-v11) update


		* Compute Number of Observations and Clinics below each test:
		foreach column in 1 2 3 4 {
		local   col_1 = `column'+1
		gen     n`column' = v`col_1'           if inlist(v1,"N","Clusters")
		}

		foreach column in 1 2 3 4  {
		destring n`column', replace
		}

		* Generate new columns for difference calculations:
		foreach column of numlist 6(1)11 {
		gen      n`column' = .
		}

		* Compute the new N's:
		replace  n6  = n1+n2
		replace  n7  = n1+n3
		replace  n8  = n1+n4
		replace  n9  = n2+n3
		replace  n10 = n2+n4
		replace  n11 = n3+n4

		* String and replace:
		foreach column of numlist 6(1)11 {
		tostring n`column', replace
		}

		foreach column of numlist 6(1)11 {
		replace v`column' = n`column'               if n`column' !="." & v`column' ==""
		}

		foreach column of numlist 2(1)5 {
		replace v`column' = ""                      if v`column' !="" & inlist(v1,"N","Clusters")
		}

		* Keep only the Control Group Mean:
		drop v3-v5
		drop n1-n11

		drop count Merge

		replace v1 = "Observations"         if v1 == "N"
		replace v1 = "Clinics"              if v1 == "Clusters"

		drop if v1 == "Clinics"

		local    agecard_fileNum = 0

		dataout, save("${Replicate_SocialSignals_ATables}/agecard_balance_at24m_`agecard_fileNum'.tex") ///
		replace tex nohead noauto

	restore




	* **************************************************************************** *
	* 4.) Loop over all remaining variables
	* **************************************************************************** *


	local VarList =  "quality_card good_memory"

	* ---------------------------------------------------------------------------- *
	* Compute ttest  mean differences
	* ---------------------------------------------------------------------------- *

	foreach balanceVar of local VarList {

	* (1) ttest mean differences

		preserve

			iebaltab  `balanceVar',  ///
			vce(cluster `clusterVar') ///
			grpvar(`treatVar') fixedeffect(`strataVar') covariates(`covariates') ///
			grplabels(1 Control @ 2 Uninformative @ 3 Signal at 4  @ 4 Signal at 5 ) order(1 2 3 4) ///
			fmissok feqtest pftest covarmissok    fnoobs   ${BalStars} ///
			rowvarlabels onerow ///
			tblnonote ///
			browse ///
			replace

			drop in 1/3

			gen     count = _n

			* Temporary save the table output
			tempfile  ttest_diff
			save   	 `ttest_diff'

		restore


		* ---------------------------------------------------------------------------- *
		* Compute ttest p-values
		* ---------------------------------------------------------------------------- *

		*  p-values

		preserve

			#d ;
			iebaltab   `balanceVar',
			vce(cluster `clusterVar')
			grpvar(`treatVar') fixedeffect(`strataVar') covariates(`covariates') ///
			grplabels(1 Control @ 2 Uninformative @ 3 Signal at 4  @ 4 Signal at 5 ) order(1 2 3 4)
			fmissok feqtest pboth covarmissok   fnoobs   ${BalStars}
			rowvarlabels onerow
			tblnonote
			browse
			replace
			;
			#d	cr

			drop in 1/3
			gen     count = _n

			drop    v2-v5

			foreach    variable of numlist 6(1)11 {
			replace v`variable' = "[" + v`variable' + "]"     if v`variable' !=""
			}
			replace count = count +1

			drop if v1 == ""

			* Temporary save the table output
			tempfile  ttest_pvals
			save   	 `ttest_pvals'
		
		restore



		* ---------------------------------------------------------------------------- *
		* Merge ttest differences & p-values
		* ---------------------------------------------------------------------------- *

		preserve

			use `ttest_diff', clear

			merge 1:1 count using `ttest_pvals', gen(Merge) keepusing(v6-v11) update


			* Compute Number of Observations and Clinics below each test:
			foreach column in 1 2 3 4 {
			local   col_1 = `column'+1
			gen     n`column' = v`col_1'           if inlist(v1,"N","Clusters")
			}

			foreach column in 1 2 3 4  {
			destring n`column', replace
			}

			* Generate new columns for difference calculations:
			foreach column of numlist 6(1)11 {
			gen      n`column' = .
			}

			* Compute the new N's:
			replace  n6  = n1+n2
			replace  n7  = n1+n3
			replace  n8  = n1+n4
			replace  n9  = n2+n3
			replace  n10 = n2+n4
			replace  n11 = n3+n4

			* String and replace:
			foreach column of numlist 6(1)11 {
			tostring n`column', replace
			}

			foreach column of numlist 6(1)11 {
			replace v`column' = n`column'               if n`column' !="." & v`column' ==""
			}

			foreach column of numlist 2(1)5 {
			replace v`column' = ""                      if v`column' !="" & inlist(v1,"N","Clusters")
			}

			* Keep only the Control Group Mean:
			drop v3-v5
			drop n1-n11

			drop count Merge

			replace v1 = "Observations"         if v1 == "N"
			replace v1 = "Clinics"              if v1 == "Clusters"


			local    `balanceVar'_fileNum = 0

			dataout, save("${Replicate_SocialSignals_ATables}/`balanceVar'_balance_at24m_``balanceVar'_fileNum'.tex") ///
			replace tex nohead noauto
			restore
		}


	* **************************************************************************** *
	* Prepare Final Table
	* **************************************************************************** *

	cap  file close _all


	local BalanceTables =  "followup agecard quality_card good_memory"


	foreach level of local BalanceTables {

		* Remove lines from `dataout` export
		foreach lineToRemove in "\BSdocumentclass[]{article}"			///
		"\BSsetlength{\BSpdfpagewidth}{8.5in}" 	///
		"\BSsetlength{\BSpdfpageheight}{11in}"  ///
		"\BSbegin{document}" 				       	///
		"\BSend{document}" 					     	///
		"\BSbegin{tabular}{lcccccccc}"			///
		"Variable"								///
		"\BShline"								///
		"\BSend{tabular}"											{

		filefilter "${Replicate_SocialSignals_ATables}/`level'_balance_at24m_``level'_fileNum'.tex"      ///
		"${Replicate_SocialSignals_ATables}/`level'_balance_at24m_`=``level'_fileNum'+1'.tex" ///
		, from("`lineToRemove'") to("") replace
		erase	     "${Replicate_SocialSignals_ATables}/`level'_balance_at24m_``level'_fileNum'.tex"

		local `level'_fileNum = ``level'_fileNum' + 1
		}

		* Add incipit and end of LaTeX table
		*(to be directly input in TeX document) without further formatting
		file open  `level'File													///
		using "${Replicate_SocialSignals_ATables}/`level'_balance_at24m_``level'_fileNum'.tex"               ///
		, text read

		* Loop over lines of the original TeX file and save everything in a local
		local 	   `level'File ""
		file read  `level'File line
		while r(eof) == 0 {
		local 	  `level'File  " ``level'File' `line' "
		file read `level'File line
		}
		file close `level'File

		* Erase original file
		erase "${Replicate_SocialSignals_ATables}/`level'_balance_at24m_``level'_fileNum'.tex"

		}



	dis "`followupFile'"
	dis "`agecardFile'"
	dis "`quality_cardFile'"
	dis "`good_memoryFile'"



	* Make final table
	file  open finalFile using "${Replicate_SocialSignals_ATables}/baltab_at24m_listingsample.tex"	///
	, text write replace

	#d	;

	file write finalFile
	"                                      & \multicolumn{1}{c}{(1)}                 & \multicolumn{1}{c}{(2)}               & \multicolumn{1}{c}{(3)}               & \multicolumn{1}{c}{(4)}                & \multicolumn{1}{c}{(5)}                 & \multicolumn{1}{c}{(6)}               & \multicolumn{1}{c}{(7)}  & \multicolumn{1}{c}{(8)}  \\"    _n      ///
	"                                       &                                        & \multicolumn{6}{c}{\textbf{t-test differences}}    & \multicolumn{1}{c}{}  \\"    _n   ///
	"                                       & \multicolumn{1}{c}{\textbf{Control}}   & \multicolumn{6}{c}{\textbf{[p-value]}}             & \multicolumn{1}{c}{}  \\"    _n   ///
	"\multicolumn{1}{l}{\textbf{Variable}}  & \multicolumn{1}{c}{\textbf{Mean/(SE)}} & \multicolumn{1}{c}{\textbf{(C)-(UI)}} & \multicolumn{1}{c}{\textbf{(C)-(S4)}} &  \multicolumn{1}{c}{\textbf{(C)-(S5)}} & \multicolumn{1}{c}{\textbf{(UI)-(S4)}} & \multicolumn{1}{c}{\textbf{(UI)-(S5)}} & \multicolumn{1}{c}{\textbf{(S4)-(S5)}} & \multicolumn{1}{c}{\textbf{F-Test}} \\ \hline \\[-2ex]"    _n    ///
	"\multicolumn{9}{l}{\textbf{\textit{Panel A: Sample Definition}}}									  	 \\ [0.5ex]  " _n
	" `followupFile' 																						                   \\ [-2ex]   " _n
	"\multicolumn{9}{l}{\textbf{\textit{Panel B: Sample Characteristics}}}				 \\ [0.5ex]  " _n
	"\addlinespace[0.75ex] `agecardFile' 													  [-2ex]  " _n
	" `quality_cardFile' 																			  	  [-2ex]  " _n
	" `good_memoryFile' 																				    \hline \hline \\ [-2ex]  " 
	;
	#d	cr

	file close finalFile


	* ******************************************************************************
	* End of the Dofile !!!
	* ******************************************************************************
